package com.egdigital.allzic;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;

import com.google.android.gcm.GCMBaseIntentService;

import fr.nomeo.APNS;
import fr.nomeo.APParameters;
import fr.nomeo.AppsPanel;
import fr.nomeo.conf.APConfManager;
import fr.nomeo.logs.APLog;
import fr.nomeo.logs.APLog.SDK;
import fr.nomeo.push.APPushDialog;
import fr.nomeo.push.APPushManager;

public class GCMIntentService extends GCMBaseIntentService {

    Context ct;
    NotificationCompat.Builder notificationBuilder;

    SharedPreferences appspanelpref;

    public GCMIntentService() {
        super(APParameters.getSenderId());

    }

    public GCMIntentService(String senderId) {
        super(senderId);
        APLog.printAPLog(SDK.PUSH, "GCMIntentService = " + senderId);
    }

    @Override
    protected void onError(Context arg0, String arg1) {
        APLog.printAPLog(SDK.PUSH, "GCM erreur");
    }

    @Override
    protected void onMessage(Context context, Intent intent) {
        
        APLog.printAPLog(SDK.PUSH, "Un push a été reçu !");

        ct = context;
        SharedPreferences appspanelpref = context.getSharedPreferences(AppsPanel.APPREF, Context.MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = appspanelpref.edit();
        

        if (APConfManager.loadSavedConfig(context)) {

            // data.message : notification text
            String originalPushMessage = intent.getStringExtra("message");

            APLog.printAPLog(SDK.PUSH, " le message brut = "+ originalPushMessage);


            //----- Format message -> message##urlWebView##persistant
            String tab[] = originalPushMessage.split("##");
            String pushMessage = tab[0];
            String urlWebView = tab[1];
            String persistant = tab[2];
            
            //Save last notification 
            prefsEditor.putString("appush_persist", persistant);
            prefsEditor.putString("appush_msg", pushMessage);
            prefsEditor.putString("appush_url", urlWebView);
            prefsEditor.putString("appush_original", originalPushMessage);
            prefsEditor.commit();

            String notificationTitle = getResources().getString(R.string.app_name);
            int notificationIconId = APParameters.getNotificationIcon();

            // Get an instance of the NotificationManager service
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
            notificationBuilder = new NotificationCompat.Builder(this).setSmallIcon(notificationIconId);

            notificationBuilder.setContentTitle(notificationTitle)
            .setContentText(pushMessage);
            
            
            String activityPackageName = ((ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1).get(0).topActivity.getPackageName() ;
            if (!context.getPackageName().equalsIgnoreCase(activityPackageName)){
               APLog.printAPLog(SDK.PUSH, "receive push app not open or in the foreground");
               
            }else{
               APLog.printAPLog(SDK.PUSH, "receive push app open");
               APPushManager.sendTrackPush(context, APParameters.ACTION_PUSH_APPOPEN,originalPushMessage);
            }
            
            Intent notifIntent = new Intent(context.getApplicationContext(),APPushDialog.class);
            notifIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notifIntent, 0);
            
            notificationBuilder.setContentIntent(contentIntent);

            setNotificationOptions();

            // Finally, launch notification
            notificationManager.notify(APPushManager.getIdnotification(context), notificationBuilder.build());
        }

    }

    @Override
    protected void onUnregistered(Context arg0, String arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onRegistered(Context context, String registrationId) {

        this.ct = context;

        // Put registrationId
        APParameters.registrationID = registrationId;
        APLog.printAPLog(SDK.PUSH, "ID PUSH = " + registrationId);

        // APPREGISTER
        if (APConfManager.loadSavedConfig(context)){
            APNS.sendDeviceInformations(context);
        }
            
    }

    private void setNotificationOptions() {

        appspanelpref = ct.getSharedPreferences(AppsPanel.APPREF,Context.MODE_PRIVATE);

        String typeNotif = appspanelpref.getString("appush_typeNotif",APParameters.NotificationType.SOUNDVIBRATE.name());
        String sonNotif = appspanelpref.getString("appush_sonNotif", null);

        // Notification disappears when pressed
        notificationBuilder.setAutoCancel(true);
        // Color led
        notificationBuilder.setLights(0xff00ff00, 300, 1000);

        if (typeNotif == APParameters.NotificationType.SOUNDVIBRATE.name()) {
            
            notificationBuilder.setVibrate(new long[] { 200, 300, 400, 500 });

            if (sonNotif != null) {
                Uri uriSon = Uri.parse("android.resource://"+ ct.getPackageName() + "/raw/" + sonNotif);
                notificationBuilder.setSound(uriSon);
            } else{
                notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
            }
            
            APLog.printAPLog(SDK.PUSH, "NOTIF TYPE = Son + Vibreur");

        } else if (typeNotif == APParameters.NotificationType.VIBRATE.name()) {

            notificationBuilder.setVibrate(new long[] { 200, 300, 400, 500 });

            APLog.printAPLog(SDK.PUSH, "NOTIF TYPE = Vibreur");

        } else if (typeNotif == APParameters.NotificationType.SOUND.name()) {

            if (sonNotif != null) { //set custom  sound
                Uri uriSon = Uri.parse("android.resource://"+ ct.getPackageName() + "/raw/" + sonNotif);
                notificationBuilder.setSound(uriSon);
            } else{
                notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
            }

            APLog.printAPLog(SDK.PUSH, "NOTIF TYPE = Son");
            
        } else if (typeNotif == APParameters.NotificationType.SILENCE.name()) {
            // DO NOTHING
            APLog.printAPLog(SDK.PUSH, "NOTIF TYPE = Silencieux");
        }
    }

}